package com.qf.boot2202day03.interceptor;


import com.qf.boot2202day03.entity.User;
import com.qf.boot2202day03.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.debug("拦截到url:{}",request.getRequestURI());

        // 判断用户是否登录过
        final HttpSession session = request.getSession();

        final User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);

        if (user == null){ // 没有登录过
            log.debug("没有登录，重定向到登录页面");
            response.sendRedirect("/login.html");
            return false;
        }
        log.debug("放行");
        return true;
    }
}
